/**
 * @param {string[]} chessboard
 * @return {number}
 */
 var flipChess = function(chessboard) {
  const h = chessboard.length;
  const w = chessboard[0].length;
  if(h < 3 && w < 3) {
    return 0;
  }
  const cboard = chessboard.map(r => r.split(''));
  const directions = [[1, 0], [1, -1], [1, 1], [0, 1], [0, -1], [-1, 1], [-1, 0], [-1, -1]];
  // const cand = {};
  let ret = 0;
  const valid = (x, y) => x >= 0 && x < h && y >= 0 && y < w; 
  // let checked = [];
  
  function check(x, y, board) {
    const temp = board;
    let total = 0;
    for(let [dx, dy] of directions) {
      if(valid(x + dx, y + dy) && board[x + dx][y + dy] === 'O') {
        let cx = x + dx * 2 , cy = y + dy * 2;
        let cnt = 1;
        while(valid(cx, cy) && board[cx][cy] === 'O') {
          cx += dx;
          cy += dy;
          cnt ++;
        }
        if(valid(cx, cy) && board[cx][cy] === 'X') {
          while(cx !== x || cy !== y) {
            board[cx][cy] = 'X';
            cx -= dx;
            cy -= dy;
          }
          cx += dx;
          cy += dy;
          while(valid(cx, cy) && board[cx][cy] === 'X') {
            cnt += check(cx, cy, board);
            cx += dx;
            cy += dy;
          }
          total += cnt;
        }
      }
    }
    return total;
  }
  for(i=0; i<h; i++) {
      for(j=0; j<w; j++) {
          if(cboard[i][j] === 'X') {
            for(let [dx, dy] of directions) {
              const board = JSON.parse(JSON.stringify(cboard));
              if(valid(i + dx, j + dy) && board[i + dx][j + dy] === 'O') {
                // console.log(i, j, dx, dy);
                let ci = i + dx * 2, cj = j + dy * 2;
                let cnt = 1;
                while(valid(ci, cj) && board[ci][cj] === 'O') {
                  ci += dx;
                  cj += dy;
                  cnt ++;
                }
                if(valid(ci, cj) && board[ci][cj] === '.') {
                  while(ci !== i || cj !== j) {
                    board[ci][cj] = 'X';
                    ci -= dx;
                    cj -= dy;
                  }
                  ci += dx;
                  cj += dy;
                  // console.log(board);
                  while(valid(ci, cj) && board[ci][cj] === 'X') {
                    cnt += check(ci, cj, board);
                    ci += dx;
                    cj += dy;
                  }
                  ret = Math.max(ret, cnt);
                }                
              }
            }
          }
      }
  }
  return ret;
};

console.log(flipChess([".XO....","......."]));